package org.hxyjs.mq.topics;

import org.hxyjs.mq.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

public class RevceTopics2 {
    private static final String EXCHANGE_NAME = "test_exchange_topic";
    private static final String QUEUE_NAME = "test_queue_topic_2";

    public static void main(String[] args) throws Exception {
        //获取连接
        Connection connection = ConnectionUtils.getConnection();

        //创建频道
        final Channel channel = connection.createChannel();

        //声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "goods.#");

        /**
         * 保证一次只分发一个
         */
        channel.basicQos(1);


        //定义队列的消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("[2] recv msg" + message);
                // 手动回执
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        boolean autoAck = false;  //自动应答

        channel.basicConsume(QUEUE_NAME, autoAck, consumer);
    }
}